package restful.struts2;

import java.io.*;
import java.util.*;

import org.apache.commons.logging.*;

import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.config.entities.*;
import com.opensymphony.xwork2.inject.*;
import com.opensymphony.xwork2.interceptor.*;

public class RestfulErrorInterceptor extends AbstractInterceptor {
	private ContentTypeHandlerManager contentTypeHandlerManager;

	private Log log = LogFactory.getLog(getClass());

	private ActionConfig configOf(ActionInvocation invocation) {
		return invocation.getProxy().getConfig();
	}

	public Map createErrorFor(Exception exception) {
		Map error = new HashMap();
		error.put("exception", exception);
		return error;
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		try {
			return proceed(invocation);
		} catch (Exception e) {
			return manageException(configOf(invocation), e);
		}
	}

	protected String manageException(ActionConfig actionConfig, Exception e) throws IOException {
		log.error(actionConfig, e);
		return contentTypeHandlerManager.handleResult(actionConfig, new DefaultHttpHeaders().disableCaching().renderResult("exception").withStatus(500), createErrorFor(e));
	}

	protected String proceed(ActionInvocation invocation) throws Exception {
		return invocation.invoke();
	}

	@Inject
	public void setContentTypeHandlerManager(ContentTypeHandlerManager contentTypeHandlerManager) {
		this.contentTypeHandlerManager = contentTypeHandlerManager;
	}

}
